package com.resou.reader.bookdetail.view;

import android.app.Activity;
import android.arch.lifecycle.LifecycleOwner;
import android.support.annotation.NonNull;

import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.BookDetailBean;
import com.resou.reader.api.entry.ChapterDataBean;
import com.resou.reader.api.entry.ChapterItemBean;
import com.resou.reader.api.entry.CommonData;
import com.resou.reader.api.service.BookService;
import com.resou.reader.base.m.IModel;
import com.resou.reader.base.p.BasePresenter;
import com.resou.reader.bookdetail.iview.ICatalogueView;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.manager.ReaderManager;
import com.resou.reader.reader.v.ReaderActivity;
import com.resou.reader.utils.CacheUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.DLog;
import com.resouxs.free_book.api.FBookFactory;
import com.resouxs.free_book.api.FBookType;
import com.resouxs.free_book.api.IFBook;
import com.resouxs.free_book.api.ZsChapterCallback;
import com.resouxs.free_book.service.ZsBookChapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ${Garrett} on 2018/9/4.
 * Contact me krouky@outlook.com
 */
public class CataloguePresenter extends BasePresenter<ICatalogueView, IModel> {

    private final IFBook fBook;
    private String mBookId;
    private BookService mService;
    private static final int PAGE_SIZE = 500;

    private List<ChapterItemBean> mList = new ArrayList<>();
    File file;
    private int mPage;
    private int mChapterSum;
    private int mPageNum;

    private String mBookName;
    private String mShareUrl;
    private String mDescription;
    private String mLastChapterName;
    private String bookPic;

    public CataloguePresenter(ICatalogueView view, String bookId, BookDetailBean bookDetailBean) {
        this.view = view;
        mBookId = bookId;
        mChapterSum = bookDetailBean.getChapterNum();
        mBookName = bookDetailBean.getNovelName();
        mShareUrl = bookDetailBean.getShareUrl();
        mDescription = bookDetailBean.getNovelDescription();
        mLastChapterName = bookDetailBean.getUpdateChapterName();
        bookPic = bookDetailBean.getCoverUrl();
        mService = ApiImp.getInstance().getService(BookService.class);
        file = new File(view.getViewContext().getCacheDir(), bookId + (UserInstance.isLogin() ? UserInstance.getToken() : 0));
        if (mChapterSum % PAGE_SIZE == 0) {
            mPageNum = mChapterSum / PAGE_SIZE;
        } else {
            mPageNum = mChapterSum / PAGE_SIZE + 1;
        }
        FBookFactory fBookFactory = new FBookFactory();
        fBook = fBookFactory.createFBook(FBookType.ZHUISHU);
    }

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        super.onCreate(owner);
//        getCatalogue(mBookId, 0, UserInstance.getUser().getToken(), DeviceUtils.getIMEI(view.getViewContext()));
    }

    /**
     * 获取章节列表
     *
     * @param bookId         @Link{BookService}
     * @param page
     * @param token
     * @param device
     * @param bookDetailBean
     */
    public void getCatalogue(final String bookId, final int page, final String token, final String device, BookDetailBean bookDetailBean) {
        mService.getBookCatalogList(bookId, null, token, device)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Function<CommonData<ChapterDataBean<List<ChapterItemBean>>>, ObservableSource<List<ChapterItemBean>>>() {
                    @Override
                    public ObservableSource<List<ChapterItemBean>> apply(CommonData<ChapterDataBean<List<ChapterItemBean>>> chapterData) throws Exception {

                        final List<ChapterItemBean> list = chapterData.getData().getData();

                        return Observable.create(new ObservableOnSubscribe<List<ChapterItemBean>>() {
                            @Override
                            public void subscribe(ObservableEmitter<List<ChapterItemBean>> emitter) throws Exception {

                                fBook.getBookChapters(bookDetailBean.getZsBookId(), bookDetailBean.getUpdateChapterName(), new ZsChapterCallback() {

                                    @Override
                                    public void onGetChapters(ZsBookChapter zsBookChapter) {
                                        checkChapterCached(list);
                                        ReaderManager.convertZsChapterToYwChapter(zsBookChapter.getChapters(), list, bookDetailBean.getZsBookId(), null);
                                        emitter.onNext(list);
                                    }

                                    @Override
                                    public void onGetChaptersFailed(String errorMsg) {
                                        checkChapterCached(list);
                                        emitter.onNext(list);
                                    }
                                });

                            }
                        });
                    }
                }).as(this.<List<ChapterItemBean>>bindLifecycle())
                .subscribe(new Consumer<List<ChapterItemBean>>() {
                    @Override
                    public void accept(List<ChapterItemBean> chapterItemBeans) throws Exception {
                        mList.clear();
                        if (chapterItemBeans != null && chapterItemBeans.size() > 0) {
                            mList.addAll(chapterItemBeans);
                            view.refresh(mList);
                        } else {
                            //没有更多数据了
                            view.refresh(mList);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        DLog.d(CataloguePresenter.class.getSimpleName(), "getCatalogue error ! msg:" + throwable.getMessage());
                        throwable.printStackTrace();
                        view.showError(throwable);
                    }
                });
    }

    private void checkChapterCached(List<ChapterItemBean> list) {
        if (list == null) {
            return;
        }
        File[] files = file.listFiles();
        for (int i = 0; i < list.size(); i++) {
            ChapterItemBean chapterItem = list.get(i);
            if (files != null) {
                for (int j = 0; j < files.length; j++) {
                    if (files[j].getName().contains(chapterItem.getChapterId())) {
                        chapterItem.setCached(true);
                        break;
                    }
                }
            }
            chapterItem.setBookId(mBookId);
            chapterItem.setChapterSum(mChapterSum);
            chapterItem.setChapterIndex(i);
            chapterItem.setBookName(mBookName);
            chapterItem.setShareUrl(mShareUrl);
            chapterItem.setDescription(mDescription);
            chapterItem.setBookPic(bookPic);
        }
    }

    public void reader(int index) {
        if (index < mList.size()) {
            ChapterItemBean bean = mList.get(index);
            ReaderActivity.startActivity((Activity) view.getViewContext(), bean, mLastChapterName);
        }
    }

    public void decideCache() {
        File[] files = file.listFiles();
        for (int i = 0; i < mList.size(); i++) {
            ChapterItemBean chapterItem = mList.get(i);
            if (files != null) {
                for (int j = 0; j < files.length; j++) {
                    if (files[j].getName().contains(chapterItem.getChapterId())) {
                        chapterItem.setCached(true);
                        break;
                    }
                }
            }
        }
        view.refresh(mList);
    }
}
